package com.example.s05_shop.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController
{

    public static final String UPLOADED_FOLDER = "./upload/";

    @RequestMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file)
    {
        System.out.println("upload!!!!");
        // 保存

        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
            // UPLOADED_FOLDER 文件本地存储地址
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        return "上传成功";

        // 返回上传成功后图片的路径
        Map<String,Object> result = new HashMap<>();
        result.put("filename",file.getOriginalFilename());
        result.put("url","/images/"+file.getOriginalFilename());

        return result;
    }
}
